package com.yaorange.controller;

import com.yaorange.dao.CustomerDao;
import com.yaorange.pojo.Customer;
import com.yaorange.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class CustomerController {
    private static SqlSession sqlSession;
    static CustomerDao customerDao;
    //初始化数据
    static {
        try {
            sqlSession = SqlSessionUtil.getSqlSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        customerDao = sqlSession.getMapper(CustomerDao.class);
    }

    //添加
    public void addCustomer(Customer customer) {
        customerDao.addCustomer(customer);
    }

    //删除
    public void deleteCustomerById(String id) {
        customerDao.deleteCustomerById(id);
        System.out.println("客户编号为" + id + "的客户删除成功！");
    }

    //批量删除
    public  void batchDelete(String ids) {
        String[] strings = ids.split("/");
        for (String s : strings) {
            //判断客户是否存在
            boolean b = ifExist(s);
            if (b) {
                //存在则删除
                deleteCustomerById(s);
            } else {
                System.out.println("不存在客户编号为" + s + "的客户,无法删除");
            }
        }
    }

    //修改
    public  void updateCustomerById(String id, String name, Date birthday, char gender) {
        if (ifExist(id)) {
            customerDao.updateCustomerById(id, name, birthday, gender);
            System.out.println("修改成功！");
        } else {
            System.out.println("查无此人，无法修改");
        }
    }

    //查找单个客户并显示
    public void queryCustomerById(String id) {
        if (ifExist(id)) {
            System.out.println(customerDao.queryCustomerById(id));
        } else {
            System.out.println("查无此人！");
        }
    }

    //判断客户是否存在
    public boolean ifExist(String id) {
        if (customerDao.queryCustomerById(id) != null) {
            return true;
        } else {
            return false;
        }
    }

    //查找全部客户并显示
    public void showCustomers() {
        List<Customer> customers = customerDao.queryAll();
        System.out.println("客户编号\t客户名称\t\t\t\t客户生日\t\t\t\t客户性别\t\t注册时间");
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        for (Customer customer : customers) {
            System.out.println();
            System.out.printf("%-8s%-19s%-17s%2c%19s", customer.getId(), customer.getName(), df.format(customer.getBirthday()), customer.getGender(), df.format(customer.getRegistTime()));
            System.out.println();
        }
    }
    //提交事务
    public void commit(){
        sqlSession.commit();
    }
    //释放资源
    public void over() {
        sqlSession.close();
    }
}
